﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CRM.Database.Model
{
    public class TrainingsRequestsCollection : AbstractCollection
    {
        /// <summary>
        /// Стaтическая коллекция 
        /// </summary>
        protected static List<TrainingsRequests> _list;

        /// <summary>
        /// Список объектов
        /// </summary>
        public List<TrainingsRequests> TrainingsRequestsList
        {
            get
            {
                return Entities.TrainingsRequests.OrderByDescending(p => p.IdTrainingsRequest).ToList();
                if (_list == null)
                    _list = DB.Entities.TrainingsRequests.ToList();
                return _list;
            }
        }

        /// <summary>
        /// Обнуление статической коллекции
        /// </summary>
        protected override void SetStaticListToNULL()
        {
            _list = null;
        }

        /// <summary>
        /// Получение статического списка для хранения объектов
        /// </summary>
        /// <returns></returns>
        public override object GetStaticCollection()
        {
            return _list;
        }

        /// <summary>
        /// Получение элемента из коллекции по идентификатору
        /// </summary>
        /// <param name="itemId">Идентификатор</param>
        /// <returns>Элемент</returns>
        public override object GetItemById(int itemId)
        {
            return Entities.TrainingsRequests.Find(itemId);
        }

        /// <summary>
        /// Возвращает список заявок, прикрепленных к выбранному расписанию.
        /// </summary>
        /// <param name="scheduleId"></param>
        /// <returns>список заявок или null</returns>
        public List<TrainingsRequests> GetTrainingsRequestesByScheduleId(int scheduleId)
        {
            var result = new List<TrainingsRequests>();
            foreach (TrainingsRequests request in TrainingsRequestsList)
            {
                if (request.IdTrainingsSchedule == scheduleId)
                    result.Add(request);
            }
            return result.Count == 0 ? null : result;
            //return result;
        }

        /// <summary>
        /// Получение списка заявок от одного клиента по ID клиента
        /// </summary>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public List<TrainingsRequests> GetTrainingsRequestsByCustomerId(int customerId)
        {
            var result = new List<TrainingsRequests>();
            foreach (TrainingsRequests request in TrainingsRequestsList)
            {
                if (request.IdCustomer != null)
                    if (request.IdCustomer == customerId)
                        result.Add(request);
            }
            return result;
        }

        /// <summary>
        /// Удаление заявки на обучение вместе со списком участников
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public new bool Delete(object item)
        {
            var request = (TrainingsRequests) item;
            if (request == null) return false;

            //удаление участников
            var participantsCol = new TrainingsParticipantsCollection();
            List<TrainingsParticipants> participantsList = participantsCol.GetParticipantsByRequest(request);
            if (participantsList != null)
            {
                foreach (TrainingsParticipants participant in participantsList)
                {
                    if (participant != null)
                        participantsCol.Delete(participant);
                }
            }

            //удаление самой заявки
            throw new NotImplementedException();
            return base.Delete(item);
        }

        #region Overrides of AbstractCollection

        /// <summary>
        /// Обновление элемента в коллекции
        /// </summary>
        /// <param name="item">Новый элемент</param>
        /// <param name="userLogin">Логин пользователя, который делает изменения</param>
        /// <returns>Результат операции</returns>
        public bool Update(object item, string userLogin, bool save = true)
        {
            var newObject = (TrainingsRequests) item;
            if (newObject == null)
                return false;

            var object4Update = GetItemByIdFromDatabase(newObject.GetKeyValue()) as TrainingsRequests;
            if (object4Update == null)
                return false;

            if (!string.IsNullOrEmpty(newObject.Company))
                object4Update.Company = newObject.Company;
            if (!string.IsNullOrEmpty(newObject.ContactName))
                object4Update.ContactName = newObject.ContactName;
            if (!string.IsNullOrEmpty(newObject.ContactPhone))
                object4Update.ContactPhone = newObject.ContactPhone;
            if (!string.IsNullOrEmpty(newObject.ContactEmail))
                object4Update.ContactEmail = newObject.ContactEmail;
            if (!string.IsNullOrEmpty(newObject.Comments))
                object4Update.Comments = newObject.Comments;
            if (!string.IsNullOrEmpty(newObject.Reason))
                object4Update.Reason = newObject.Reason;

            object4Update.IdTrainingsSchedule = newObject.IdTrainingsSchedule;
            object4Update.RequestDate = newObject.RequestDate;
            object4Update.IdTrainingsRequestsStatus = newObject.IdTrainingsRequestsStatus;
            object4Update.IdCustomer = newObject.IdCustomer;
            object4Update.FirstDate = newObject.FirstDate;
            object4Update.LastDate = newObject.LastDate;
            object4Update.IdTrainingsCourse = newObject.IdTrainingsCourse;
            object4Update.IdLegalEntity = newObject.IdLegalEntity;
            object4Update.IdContact = newObject.IdContact;
            object4Update.DateOfRegisterMail = newObject.DateOfRegisterMail;
            object4Update.DateOfAcceptMail = newObject.DateOfAcceptMail;
            object4Update.DateOfDeclineMail = newObject.DateOfDeclineMail;
            object4Update.DateOfManagerMail = newObject.DateOfManagerMail;

            //if (object4Update.PredictParticipantsCount != null)
                object4Update.PredictParticipantsCount = newObject.PredictParticipantsCount;
            //if (object4Update.IdTrainingsAuditorium != null)
                object4Update.IdTrainingsAuditorium = newObject.IdTrainingsAuditorium;

            return base.Update(object4Update, userLogin, save);
        }

        /// <summary>
        /// Получение списка элементов
        /// </summary>
        /// <returns>Список элементов</returns>
        public override List<object> GetList()
        {
            return new List<object>(TrainingsRequestsList);
        }

        /// <summary>
        /// Получение типа текущего элемента
        /// </summary>
        /// <returns></returns>
        protected override Type GetItemType()
        {
            return typeof (TrainingsRequests);
        }

        #endregion
    }
}